const _ = require('../utils')
const constants = require('../constants')

_.create('backdrop', {
  properties: {
    show: {
      type: Boolean,
      value: false,
    },
    position: {
      type: String,
      value: 'center',
    },
    duration: {
      type: Number,
      value: constants.animation.durationNormal,
    },
    mask: {
      type: Boolean,
      value: true,
    },
  },

  data: {
    visibility: 'hidden',
  },

  observers: {
    show: function (show) {
      const { visibility } = this.data
      if (show && visibility === 'hidden') {
        this.setData({ visibility: 'visible' })
        wx.nextTick(() => this._animIn())
      } else if (visibility === 'visible') {
        this._animOut()
      }
    },

    position: function (pos) {
      let contentPosition
      switch (pos) {
        case 'top':
          contentPosition = 'flex-start'
          break
        case 'bottom':
          contentPosition = 'flex-end'
          break
        default:
          contentPosition = 'center'
          break
      }
      this.setData({ contentPosition })
    },
  },

  methods: {
    onTap(e) {
      this.triggerEvent('tap', e.detail)
    },

    _animIn() {
      const keyframes = [
        { opacity: 0, ease: constants.animation.easeOutQuad },
        { opacity: 1, ease: constants.animation.easeOutQuad },
      ]
      this.animate('#wrapper', keyframes, this.data.duration, () => {
        this.triggerEvent('show')
      })
    },

    _animOut() {
      const keyframes = [
        { opacity: 1, ease: constants.animation.easeInQuad },
        { opacity: 0, ease: constants.animation.easeInQuad },
      ]
      // console.log('anim out start')
      this.animate('#wrapper', keyframes, this.data.duration, () => {
        // console.log('anim out finished')
        this.setData({ visibility: 'hidden' })
        this.clearAnimation('#wrapper')
        this.triggerEvent('hide')
      })
    },
  },
})
